Telegram Group & Telegram Channel
🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci



tg-me.com/csharp_ci/1371
Create:
Last Update:

🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1371

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

Telegram Be The Next Best SPAC

I have no inside knowledge of a potential stock listing of the popular anti-Whatsapp messaging app, Telegram. But I know this much, judging by most people I talk to, especially crypto investors, if Telegram ever went public, people would gobble it up. I know I would. I’m waiting for it. So is Sergei Sergienko, who claims he owns $800,000 of Telegram’s pre-initial coin offering (ICO) tokens. “If Telegram does a SPAC IPO, there would be demand for this issue. It would probably outstrip the interest we saw during the ICO. Why? Because as of right now Telegram looks like a liberal application that can accept anyone - right after WhatsApp and others have turn on the censorship,” he says.

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

C C Sharp programming from sa


Telegram C# (C Sharp) programming
FROM USA